package com.mdinfo.base.utils;


import com.mdinfo.base.common.bean.CommonResult;
import com.mdinfo.base.common.bean.Ref;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * Created by superbone on 2017/10/26.
 */
public class ValidateUtil {

    public static <T> CommonResult<T> validate(Object obj){
        Validator validator = Validation.buildDefaultValidatorFactory()
                .getValidator();

        //验证某个对象,，其实也可以只验证其中的某一个属性的
        Set<ConstraintViolation<Object>> constraintViolations = validator
                .validate(obj);

        //如果验证后的集合为空,表示验证通过.返回验证成功
        if(constraintViolations==null || constraintViolations.size()==0){
            return Ref.ok();
        }

        //验证不成功,写入buff中
        StringBuffer buffer = new StringBuffer();
        constraintViolations.forEach(item->{
            buffer.append(item.getMessage()+" ");
        });
        return Ref.paramError(buffer.toString());
    }
}
